<script setup>
import {useRouter} from "vue-router";
import {HTTP} from "@/api/HTTP.js";
import clipboard from 'clipboard'
import {ref, onMounted} from "vue";
import useCity from "@/stores/City/index.js";
import {CircleCheck, CopyDocument, Delete, Edit, Star} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";

const city = useCity()
const router = useRouter()
const handleBack = () => {
  router.back()
}

// 获取订单信息
const address_data = ref([])
const copyData = ref('')
const fetchAddressData = async () => {
  try {
    const response = await HTTP.get('/user/addr');
    address_data.value = response.data?.list

    if (Object.keys(response.data).length === 0 || response.data.list.length === 0) {
      ElMessage({
        message: '暂无地址信息',
        type: 'warning'
      });
    }
  } catch (e) {
    console.error('Error fetching address data:', e);
  }
};


// 把信息复制到粘贴板
const handleCopy = (item) => {
  copyData.value = item.consignee + '\n' + item.addressNumber.detail + '\n' + item.consigneePhone
  clipboard.copy(copyData.value)
  ElMessage({
    message: '复制成功',
    type: 'success',
  })
}

// 删除地址
const handleDelete = async (item) => {
  try {
    const response = await HTTP.delete(`/user/address`, {
      params: {
        addressId: String(item.addressNumber.addressId)
      }
    });

    if (response.code === 10200) {
      ElMessage({
        message: '删除成功',
        type: 'success'
      });
      await fetchAddressData();
    } else {
      ElMessage({
        message: '删除失败',
        type: 'error'
      });
    }
  } catch (error) {
    ElMessage({
      message: '删除失败',
      type: 'error'
    });
    console.error('Error deleting address:', error);
  }
};

// 提交新地址
const form = ref({
  detail: '',
  consignee: '',
  consigneePhone: ''
})

// 点击提交
const onSubmit = async () => {
  let formData = new FormData();
  formData.append('consignee', form.value.consignee);
  formData.append('consigneePhone', form.value.consigneePhone);
  formData.append('detail', form.value.detail);
  try {
    await HTTP.post('/user/addr', formData).then(async (response) => {
      if (response.code === 10200) {
        ElMessage({
          message: '添加成功',
          type: 'success'
        });
        form.value = {
          detail: '',
          consignee: '',
          consigneePhone: ''
        }
        await fetchAddressData();
      } else {
        ElMessage({
          message: '添加失败',
          type: 'error'
        });
      }
    })

  } catch (e) {
    ElMessage({
      message: '发生错误',
      type: 'error'
    });
    console.error(e);
  }
};
// 控制修改对话框
const dialogFormVisible = ref(false)
const formLabelWidth = ref('100px')
// 保存表单数据
const editForm = ref({
  consignee: '',
  consigneePhone: '',
  detail: '',
  isDefault: false
})

// 点击修改按钮
const handleEdit = async (item) => {
  dialogFormVisible.value = true
  editForm.value = {
    consignee: item.consignee,
    addressId: String(item.addressNumber.addressId),
    consigneePhone: item.consigneePhone,
    detail: item.addressNumber.detail,
    isDefault: Number(item.defaultId) === item.addressNumber.addressId
  }
  console.log(editForm.value)
}


// 点击修改按钮
const onEdit = async () => {
  try {
    if (editForm.value.consignee === '' || editForm.value.consigneePhone === '' || editForm.value.detail === '') {
      ElMessage({
        message: '请填写完整信息',
        type: 'warning'
      });
      return
    }
    let editFormData = new FormData();
    editFormData.append('addressId', editForm.value.addressId);
    editFormData.append('consignee', editForm.value.consignee);
    editFormData.append('consigneePhone', editForm.value.consigneePhone);
    editFormData.append('detail', editForm.value.detail);
    editFormData.append('isDefault', editForm.value.isDefault);
    const response = await HTTP.put('/user/addr', editFormData);
    console.log(response)
    if (response.code === 10200) {
      ElMessage({
        message: '修改成功',
        type: 'success'
      });
      await fetchAddressData();
    } else {
      ElMessage({
        message: '修改失败',
        type: 'error'
      });
    }
  } catch (e) {
    ElMessage({
      message: '修改失败',
      type: 'error'
    });
  } finally {
    dialogFormVisible.value = false
  }
}
//  页面加载时执行
onMounted(() => {
  fetchAddressData();
});
</script>

<template>
  <div class="address">

    <div class="address_main">
      <h1>
        <i class="iconfont icon-fanhui4"
           @click="handleBack"
        ></i>
      </h1>
      <h2>地址管理</h2>
      <ul>
        <li v-for="item in address_data" :key="item.addressNumber.addressId">
          <div class="address_item">
            <div class="address_left">
              <p>昵称：{{ item.consignee }}</p>
              <p>手机号：{{ item.consigneePhone }}</p>
              <p>详细地址：{{ item.addressNumber.detail }}</p>
              <el-tag v-show="Number(item.defaultId) === item.addressNumber.addressId" type="danger">默认地址</el-tag>
            </div>
            <div class="address_right">
              <div>
                <div>
                  <el-button type="warning" @click="handleEdit(item)" :icon="Edit" round/>
                </div>
                <div style="height: 50px">
                </div>
              </div>
              <div>
                <div>
                  <el-button type="primary" @click="handleCopy(item)" :icon="CopyDocument" round/>
                </div>
                <div>
                  <el-button type="danger" @click="handleDelete(item)" :icon="Delete" round/>
                </div>
              </div>
            </div>
          </div>
          <br>
        </li>
      </ul>
    </div>

    <!-- 编辑对话框-->
    <el-dialog v-model="dialogFormVisible" title="编辑地址" width="500">
      <el-form :model="editForm">
        <el-form-item label="收件人姓名：" :label-width="formLabelWidth">
          <el-input v-model="editForm.consignee" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="联系方式：" :label-width="formLabelWidth">
          <el-input v-model="editForm.consigneePhone" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="收件地址：" :label-width="formLabelWidth">
          <el-input v-model="editForm.detail" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="默认地址·" :label-width="formLabelWidth">
          <el-switch v-model="editForm.isDefault"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="onEdit">
            修改
          </el-button>
        </div>
      </template>
    </el-dialog>

    <div class="address_main_right">
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="收货人姓名：">
          <el-input v-model="form.consignee"/>
        </el-form-item>
        <el-form-item label="收货人手机号：">
          <el-input v-model="form.consigneePhone"/>
        </el-form-item>
        <el-form-item label="收货人地址">
          <el-input v-model="form.detail"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">创建新地址</el-button>
        </el-form-item>
      </el-form>


      <div class="position_cat">
        <img src="@/assets/icon/cat.png" alt="">
        <p>你的支持很 valued!</p>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.address {
  width: 1535px;
  height: 100vh;
  overflow: hidden;
  display: flex;
  margin: 0 auto;


  .address_main {
    width: 1000px;
    height: 90vh;
    overflow-y: scroll;

    h1 {
      i {
        cursor: pointer;
        font-size: 40px;
        font-weight: bold;
      }
    }

    h2 {
      margin-left: 20px;
    }

    .address_item {
      margin: 20px 30px;
      border-radius: 20px;
      width: 800px;
      display: flex;
      justify-content: space-between;
      height: 150px;
      border: 2px solid black;

      .address_left {
        width: 800px;
        height: auto;
        padding: 20px;
      }

      .address_right {
        width: 150px;
        height: 100%;
        display: flex;
        justify-content: space-evenly;

        div {
          width: 50px;
          display: flex;
          justify-content: space-evenly;
          align-items: center;
          flex-direction: column;

          .el-button {
            width: 50px;
            font-size: 30px;
            height: 50px;
          }
        }
      }
    }

  }

  .address_main_right {
    width: 600px;
    height: 100%;
    margin-left: 20px;
    padding: 100px 0;

    .el-form-item {
      margin: 30px 0;

      .el-input {
        height: 50px;
      }

      .el-button {
        margin-left: 110px;
        height: 40px;
        font-size: 18px;
      }
    }

    .position_cat {
      margin-left: 50px;
      width: 500px;
      position: relative;
      border: 2px dashed black;
      border-radius: 20px;
      margin-top: 150px;

      p {
        position: absolute;
        bottom: 6px;
        font-weight: bold;
        left: 5px;
        font-size: 18px;
      }
    }
  }
}
</style>